<template>
  <div class="category-add-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900 ">添加分类</h1>
        </div>
        <div class="flex space-x-3">
          <el-button type="success" @click="handleSave" :loading="saving" class="w-[90px]">
            保存
          </el-button>
          <el-button type="default" @click="handleCancel" class="w-[90px]">
            取消
          </el-button>
        </div>
      </div>
    </div>

    <!-- 使用共享的分类表单组件 -->
    <div class="form-container">
      <CategoryForm
        ref="categoryFormRef"
        mode="add"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import CategoryForm from '~/components/admin/CategoryForm.vue'
import { categoryAPI } from '~/services/api'

// 定义页面布局
definePageMeta({
  layout: 'admin'
})

const router = useRouter()
const categoryFormRef = ref()
const saving = ref(false)

// 保存分类
const handleSave = async () => {
  try {
    saving.value = true
    
    // 验证表单
    const valid = await categoryFormRef.value?.validate()
    if (!valid) return
    
    // 获取表单数据
    const formData = categoryFormRef.value?.getFormData()
    
    // 调用后端API添加分类
    await categoryAPI.addCategory(formData)
    
    ElMessage.success('分类添加成功')
    router.push('/admin/category/list')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/admin/category/list')
}
</script>

<style scoped>
.category-add-page {
  @apply min-h-screen bg-gray-50 ;
}

.page-header {
  @apply bg-white  shadow-sm border-b border-gray-200  px-6 py-4 mb-6;
}

.form-container {
  @apply px-6 pb-6;
}
</style>


